# (c) J.Y.Amihud 2023
# GPL-3 or any later version

# This is a script that should let people download.

import os
import json
import time
import hashlib
import urllib.request
import urllib.parse
import subprocess

website = "https://bass.madiator.cloud"
#website = "http://4n3qimgvdr64ay2cbiqjw3e6fj73vbjnc3dagzxb7kov36gyixstk2yd.onion"
#website = "http://localhost:8080"
project = "Morias_Race_Sources"


# Colors are used to make the
clr = {
    "norm":"\033[00m", # Reset to normal
    "bold":"\033[01m", # Bold Text
    "ital":"\033[03m", # Italic Text
    "undr":"\033[04m", # Underlined
    "blnk":"\033[05m", # Blinking

    # Text
    "tdbl":"\033[30m", # Dark Black
    "tdrd":"\033[31m", # Dark Red
    "tdgr":"\033[32m", # Dark Green
    "tdyl":"\033[33m", # Dark Yellow
    "tdbu":"\033[34m", # Dark Blue
    "tdma":"\033[35m", # Dark Magenta
    "tdcy":"\033[36m", # Dark Cyan
    "tdwh":"\033[37m", # Dark White

    "tbbl":"\033[90m", # Bright Black
    "tbrd":"\033[91m", # Bright Red
    "tbgr":"\033[92m", # Bright Green
    "tbyl":"\033[93m", # Bright Yellow
    "tbbu":"\033[94m", # Bright Blue
    "tbma":"\033[95m", # Bright Magenta
    "tbcy":"\033[96m", # Bright Cyan
    "tbwh":"\033[97m", # Bright White

    # Background
    "bdbl":"\033[40m", # Dark Black
    "bdrd":"\033[41m", # Dark Red
    "bdgr":"\033[42m", # Dark Green
    "bdyl":"\033[43m", # Dark Yellow
    "bdbu":"\033[44m", # Dark Blue
    "bdma":"\033[45m", # Dark Magenta
    "bdcy":"\033[46m", # Dark Cyan
    "bdwh":"\033[47m", # Dark White

    "bbbl":"\033[100m", # Bright Black
    "bbrd":"\033[101m", # Bright Red
    "bbgr":"\033[102m", # Bright Green
    "bbyl":"\033[103m", # Bright Yellow
    "bbbu":"\033[104m", # Bright Blue
    "bbma":"\033[105m", # Bright Magenta
    "bbcy":"\033[106m", # Bright Cyan
    "bbwh":"\033[108m"  # Bright White
}


# LOGO
logo = open("big_logo.txt")
logo = logo.read()
print()
print(logo)
print()
print("              type 'help' to start")
print()


def csize(x):

    x = float(x)

    l = ["B","KB", "MB", "GB", "TB"]

    for i in range(5):
        if x > 1024:
            x = x / 1024
        else:
            return str(round(x, 2))+" "+l[i]
    return str(round(x, 2))+" "+l[i]

def pb(percent, action=""):

    percent = max(0, min(100, percent))
    percent = round(percent, 2)
    print("\r    "+clr["bold"]+str(percent)+"%"+clr["tdyl"]+" ["+("#"*int(percent/5))+(" "*int(20-(percent/5)))+"] "+clr["norm"]+action+"                              ", end=clr["norm"])
    


    
# RESPONSE

def go(path):

    url = website+path
    response = urllib.request.urlopen(url)
    data = response.read()
    text = data.decode("utf-8")
    data = json.loads(text)
    
    return data

def down(cur, filename, pp=0, pf=100, filesize=0):

    
    if filename.endswith(".blend"):

        dp = go("/blend"+cur+filename)
        
        # cp = (pp+(pf*0.1))
        # pb(cp, "["+clr["bold"]+filename+clr["norm"]+"]")
        
        dplen = len(dp.get("files", {}))
        
        for f in dp.get("files", {}):
            try:
                hashis = hashlib.md5(open(project+f,'rb').read()).hexdigest()
            except:
                hashis = ""
            if hashis != dp.get("files", {}).get(f, {}).get("md5"):
                
                pp = down( f[:f.rfind("/")+1],
                           f[f.rfind("/")+1:],
                           pp=pp,
                           pf=pf/dplen,
                           filesize=dp.get("files", {}).get(f, {}).get("filesize",0))

    try:
        os.makedirs(os.getcwd()+"/"+project+cur)
        #print("    📁 Making Directory: "+project+cur+" ...")
    except:
        pass


    
    cp = pp+pf
    pb(min(cp, 98), clr["bold"]+filename+clr["norm"]+" ("+csize(filesize)+")")
    
    url = website+"/download"+cur+filename
    response = urllib.request.urlopen(url)
    savef = open(project+cur+filename, "wb")
    savef.write(response.read())
    savef.close()

    
    
    return cp

# HELP

def help():

    print("""
    
    This is a very simple program.
    Here are the commands:

    help - Shows this help.
    exit - Exits the software.
    
    ls - List file in the current folder
    cd [folder name] - Change directory
    op [file name] - Get and Open File


""")

# LIST
    
def ls(cur):

    data = go("/list"+cur)
    for folder in data.get("folders", []):
        print("    📁"+clr["tdyl"]+" "+folder)

    for f in data.get("files", []):
        print("    📄"+clr["tbbu"]+" "+f)


        
    print(clr["norm"])

# CHANGE DIRECTORY
    
def cd(cur, where):

    if where != "..":
        data = go("/list"+cur)
        if where in data.get("folders", []):
            globals()["cur"] = cur+where+"/"
    else:
        globals()["cur"] = cur[:cur[:-1].rfind("/")+1]
        if not globals()["cur"]:
            globals()["cur"] = "/"

# OPEN
            
def op(cur, filename):
    data = go("/list"+cur)
    if filename in data.get("files", {}):

        # Checking hash

        #print("    ✅ Checking MD5 Hash...")
        pb(0, clr["bold"]+filename+clr["norm"])
        
        try:
            hashis = hashlib.md5(open(project+cur+filename,'rb').read()).hexdigest()
        except:
            hashis = ""

        # Downloading
            
        if hashis != data.get("files", {}).get(filename, {}).get("md5"):

            down(cur, filename,
                 filesize=data.get("files", {}).get(filename, {}).get("filesize",0))

        pb(100, clr["bold"]+filename+clr["norm"])
        print()
            
        # Opening
        subprocess.Popen(["xdg-open", project+cur+filename], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
        
        print(clr["norm"])
    
    
cur = "/"

# MAIN LOOP

while True:

    c = input("  📁 "+clr["tbyl"]+cur.replace("/", clr["tbbu"]+clr["bold"]+" > "+clr["norm"]+clr["tbyl"])+clr["norm"]+" ")

    
    if c == "help":
        help()
    elif c == "exit":
        exit()
    elif c == "ls":
        ls(cur)
    elif c.startswith("cd "):
        cd(cur, c[3:])
    elif c.startswith("op "):
        op(cur, c[3:])
